﻿using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;

namespace Avivo.Common
{
	public class Helper
	{
		public static string JsonSerialize(object json)
		{
			using (var stream = new MemoryStream())
			{
				var serializer = new DataContractJsonSerializer(json.GetType());
				serializer.WriteObject(stream, json);
				stream.Position = 0;

				using (var reader = new StreamReader(stream, Encoding.UTF8))
				{
					return reader.ReadToEnd();
				}
			}
		}

		public static T JsonDeserialize<T>(string json)
		{
			using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
			{
				var serializer = new DataContractJsonSerializer(typeof(T));
				return (T)serializer.ReadObject(stream);
			}
		}

		public static string XmlSerialize(object obj)
		{
			var serializer = new DataContractSerializer(obj.GetType());
			using (var stream = new MemoryStream())
			{
				serializer.WriteObject(stream, obj);
				byte[] data = stream.ToArray();
				string xml = Encoding.UTF8.GetString(data, 0, data.Length);
				return xml;
			}
		}

		public static T XmlDeserialize<T>(string xml)
		{
			var serializer = new DataContractSerializer(typeof(T));
			using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
			{
				var result = (T)serializer.ReadObject(stream);
				return result;
			}
		}

		public static char GetFreeDriveLetter()
		{
			//Find all taken drive letters
			var letters = new List<char>();
			var drives = DriveInfo.GetDrives();
			foreach (var drive in drives)
			{
				letters.Add(drive.Name.ToUpper()[0]);
			}

			//Find the first free drive letter
			for (char c = 'D'; c <= 'Z'; c++)
			{
				if (!letters.Contains(c))
				{
					return c;
				}
			}

			throw new DriveNotFoundException("No drive letter available to mount!");
		}
	}
}
